package cn.itsource.org.service.impl;

import cn.itsource.basic.dto.UserSmsCodeDto;
import cn.itsource.basic.exception.BusinessException;
import cn.itsource.basic.util.MD5Utils;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.org.domain.Logininfo;
import cn.itsource.org.domain.User;
import cn.itsource.org.mapper.LogininfoMapper;
import cn.itsource.org.mapper.UserMapper;
import cn.itsource.org.service.IUserService;
import cn.itsource.basic.service.Impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mochen
 * @since 2023-03-27
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void register(UserSmsCodeDto urDto) {
//        1. 参数校验
//        2. 验证码校验

        //从用户传进来的东西拼redis里的key
        String redisKey = urDto.getPhone()+":"+"register";
        Object redisValue = redisTemplate.opsForValue().get(redisKey);

        if (redisValue == null){
            throw new BusinessException("短信验证码无效!");
        }
        String code = redisValue.toString().split(":")[0];
        if (!code.equals(urDto.getSmsCode())){
            throw new BusinessException("短信验证码错误!");
        }
//        3. 密码校验
        if (urDto.getPassword().equals("") || urDto.getPasswordRepeat().equals("")){
            throw new BusinessException("请输入密码!");
        }
        if (!urDto.getPassword().equals(urDto.getPasswordRepeat())){
            throw new BusinessException("密码输入不一致!");
        }
        //加密   --->加盐加密
        String salt = StrUtils.getComplexRandomString(16);
        String pwdInDB = MD5Utils.encrypByMd5(urDto.getPassword() + salt);
//        4. 保存logininfo
        Logininfo logininfo = saveLogininfo(urDto, salt, pwdInDB);
//        5. 保存user
        logininfo2User(logininfo);
    }

    public User logininfo2User(Logininfo logininfo) {
        User user = new User();
        BeanUtils.copyProperties(logininfo,user);
        user.setCreateTime(new Date());
        user.setState(1);
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
        return user;
    }

    public Logininfo saveLogininfo(UserSmsCodeDto urDto, String salt, String pwdInDB) {
        Logininfo logininfo = new Logininfo();
        logininfo.setUsername(urDto.getPhone());
        logininfo.setPhone(urDto.getPhone());
        logininfo.setDisable(1);
        logininfo.setPassword(pwdInDB);
        logininfo.setSalt(salt);
        logininfo.setType(1);
        logininfoMapper.save(logininfo);
        return logininfo;
    }
}
